﻿
#include "CreateSphereDlg.h"

CreateSphereDlg::CreateSphereDlg(QWidget* parent):
    DlgBase(parent)
{
    initUI();
    manageConnections();
}

CreateSphereDlg::~CreateSphereDlg()
{
}

void CreateSphereDlg::initUI()
{
    setWindowTitle("Create Sphere");
    QVBoxLayout* pDlgLayout = new QVBoxLayout(this);  //create layout

    {
        m_centerEdit = new MyCoordinateEdit(this, "Center Point");
        m_centerEdit->setValues(5, 0, 0);
        pDlgLayout->addWidget(m_centerEdit);

        m_radiusEdit = new MyDoubleEdit(this, "Radius");
        m_radiusEdit->setValue(1.0);
        pDlgLayout->addWidget(m_radiusEdit);
    }

    {
        m_okBtn = new QPushButton("OK", this);
        m_cancelBtn = new QPushButton("Cancel", this);

        QHBoxLayout* okCancelLayout = new QHBoxLayout(this);
        okCancelLayout->addWidget(m_okBtn);
        okCancelLayout->addWidget(m_cancelBtn);
        pDlgLayout->addLayout(okCancelLayout);
    }

    this->setLayout(pDlgLayout);
}


bool CreateSphereDlg::create()
{
    auto pVtkViewWindow = MyVtkViewWindow::GetInstance();
    if(pVtkViewWindow == nullptr)
    {
        return false;
    }

    {
        m_centerEdit->getValues(m_centerPoint[0], m_centerPoint[1], m_centerPoint[2]);
        m_radius = m_radiusEdit->getValue();

        //创建 sphere
        vtkSmartPointer<vtkSphereSource> sphereSource = vtkSmartPointer<vtkSphereSource>::New();
        sphereSource->SetCenter(m_centerPoint);
        sphereSource->SetRadius(m_radius);
        sphereSource->SetPhiResolution(QtVtkModle::Global::SpherePhiResolution);
        sphereSource->SetThetaResolution(QtVtkModle::Global::SphereThetaResolution);
        sphereSource->Update();

        vtkSmartPointer<vtkPolyDataMapper> sphereMapper = vtkSmartPointer<vtkPolyDataMapper>::New();
        sphereMapper->SetInputConnection(sphereSource->GetOutputPort());
        sphereMapper->StaticOn();//设置静态属性，提高渲染效率(提升40%)

        vtkSmartPointer<vtkActor> sphereActor = vtkSmartPointer<vtkActor>::New();
        sphereActor->SetMapper(sphereMapper);
        sphereActor->GetProperty()->SetColor(QtVtkModle::Global::SphereColor[0], QtVtkModle::Global::SphereColor[1], QtVtkModle::Global::SphereColor[2]);  //set sphere color

        //add sphere to vtk view
        pVtkViewWindow->GetRenderer()->AddActor(sphereActor);
        GetActorManagerInstance()->AddActor(sphereActor, PickMode::FACE);
    }

    pVtkViewWindow->GetRenderer()->ResetCamera();
    pVtkViewWindow->GetRenderWindow()->Render();
    return true;
}

void CreateSphereDlg::manageConnections()
{
    connect(m_okBtn, &QPushButton::clicked, this, [=]()
            {
                if(create())
                {
                    close();
                }
                else
                {
                    QMessageBox::warning(this, "Error", "Failed to create sphere!");
                }
            });

    connect(m_cancelBtn, &QPushButton::clicked, this, &CreateSphereDlg::close);
}




